package com.nuanshui.heatedloan.controller.display.credit;

import com.aipg.rnp.RNPCRET;
import com.aipg.rnp.RNPCRETCODE;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.nuanshui.framework.lang.SysStringUtils;
import com.nuanshui.heatedloan.constant.GlobalParam;
import com.nuanshui.heatedloan.controller.BaseController;
import com.nuanshui.heatedloan.credit.constant.smsResponseType;
import com.nuanshui.heatedloan.credit.facade.*;
import com.nuanshui.heatedloan.credit.facade.third.party.RiskManagerInteractionService;
import com.nuanshui.heatedloan.credit.model.CustomerRepayMsg;
import com.nuanshui.heatedloan.credit.pay.PayRequest;
import com.nuanshui.heatedloan.credit.pay.PayResult;
import com.nuanshui.heatedloan.credit.vo.PayOrderInfoVO;
import com.nuanshui.heatedloan.msgcenter.facade.VerificationFacade;
import com.nuanshui.heatedloan.userinfo.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zss
 * @date 2017/7/12 19:45
 * @description 用户还款Controller
 * @Since
 */
@RequestMapping("credit/payment")
@RestController
public class CustomerRepayController  extends BaseController {

    private Logger logger= LoggerFactory.getLogger(CustomerRepayController.class);

    @Reference(url= GlobalParam.CREDIT_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.CREDIT_DUBBO_SERVER_VERSION)
    private CustomerBankCardInfoService customerBankCardInfoService;

    @Reference(url= GlobalParam.CREDIT_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.CREDIT_DUBBO_SERVER_VERSION)
    private PayOrderInfoService payOrderInfoService;

    @Reference(url= GlobalParam.CREDIT_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.CREDIT_DUBBO_SERVER_VERSION)
    public CustomerCreditResultService customerCreditResultService;

    @Reference(url= GlobalParam.CREDIT_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.CREDIT_DUBBO_SERVER_VERSION)
    public AllinPayTransService allinPayTransService;

    @Reference(url=GlobalParam.CREDIT_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.CREDIT_DUBBO_SERVER_VERSION)
    private CustomerIdCardInfoService customerIdCardInfoService;

    @Reference(url = GlobalParam.MSGCENTER_DUBBO_SERVER, timeout = GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.MSGCENTER_DUBBO_SERVER_VERSION )
    private VerificationFacade veriFacade;

    @Reference(url = GlobalParam.MSGCENTER_DUBBO_SERVER, timeout = GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.MSGCENTER_DUBBO_SERVER_VERSION )
    private RiskManagerInteractionService riskManagerInteractionService;

    @Reference(url = GlobalParam.CREDIT_DUBBO_SERVER, timeout = GlobalParam.DUBBO_SERVER_TIME_OUT,version=GlobalParam.CREDIT_DUBBO_SERVER_VERSION )
    private AllinPayAuthService allinPayAuthService;

    @Reference(url = GlobalParam.CREDIT_DUBBO_SERVER, timeout = GlobalParam.DUBBO_SERVER_TIME_OUT,version=GlobalParam.CREDIT_DUBBO_SERVER_VERSION )
    private ApplyOrderService applyOrderService;

    @RequestMapping(value = "/load",method = RequestMethod.POST)
    public String loadRepayInfo(String orderNo){
        Map<String,Object> resultMap=new HashMap<String,Object>();
        User user= getCurrentUser();
        resultMap.put("payInfo",payOrderInfoService.loadVOByOrderNo(orderNo));//订单信息
        resultMap.put("cardInfo",customerBankCardInfoService.loadLatestVOByUserId(user.getId()));//最新银行卡信息
        return  success(resultMap);
    }

    @RequestMapping(value = "/confirm",method = RequestMethod.POST)
    public String repay(String repayMsg){ //用户还款
        Map<String,Object> resultMap=new HashMap<String,Object>();
        User user= getCurrentUser();
        CustomerRepayMsg msg = JSON.parseObject(repayMsg, CustomerRepayMsg.class);
        String code=msg.getSmsCode();
        if (SysStringUtils.isEmpty(msg.getSmsErrorCode())||
                smsResponseType.SMS_RESPONSE_FAIL.equals(msg.getSmsErrorCode())){//验证码校验状态为空或者为失败状态都要再次验证
            RNPCRET result=allinPayAuthService.authRepayUserAccountVerify(user.getId(),code);
            boolean flag = (result==null || result.getRET_CODE().equals(RNPCRETCODE.VERYIFY_FAIL));
            if(flag){
                logger.info("------验证码验证出错-----");
                resultMap.put("smsErrorCode", smsResponseType.SMS_RESPONSE_FAIL);
                return success(resultMap);
            }else {
                logger.info("------验证码验证通过-----");
                resultMap.put("smsErrorCode", smsResponseType.SMS_RESPONSE_SUCCESS);
            }
        }
        int payAmount = (Integer.parseInt(msg.getPayAmount()));//这个orderAmount是本金+利息+逾期费用
        PayOrderInfoVO payOrderInfoVO = payOrderInfoService.loadVOByOrderNo(msg.getOrderNo());
        int amount=payOrderInfoVO.getPayAmount();
        if(payAmount != amount){
           return error("还款金额出现错误");
        }
        PayResult payResult = applyOrderService.repayMoney(payOrderInfoVO,msg.getMixCardNo());
        resultMap.put("payResult",payResult);
        if (1 == payResult.getCode()){//还款成功
            resultMap.put("loanAmount",payOrderInfoService.loadUserLoanAmount(user.getId()));
            resultMap.put("loanCount",payOrderInfoService.loadUserLoanAccount(user.getId()));
        }
        return  success(resultMap);
    }

    /**
     * 弃用
     * 处理扣款
     * @param payOrderInfoVO
     * @return
     */
    private PayResult dealReceivePay(PayOrderInfoVO payOrderInfoVO,String mixCardNo){
        PayRequest request=new PayRequest();
        request.setUserId(getCurrentUser().getId());
        request.setOrder(payOrderInfoVO);
        request.setMixCardNo(mixCardNo);

        String orderId=payOrderInfoVO.getOrderNo();
        //单期贷
        String bizType=allinPayTransService.getPayBizType(orderId);
        if(SysStringUtils.isNotEmpty(bizType))
        {
            request.setBizType(bizType);
        }
        PayResult payResult = allinPayTransService.repayFund(request);
        return payResult;
    }

}
